package com.aurora.app.controller;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.aurora.app.service.UserService;
import com.aurora.app.service.WeixinService;
import com.aurora.app.util.weixin.WeixinMediaUtil;
import com.aurora.base.util.CreateResJosnUtil;
import com.aurora.base.util.UploadUtil;
import com.aurora.app.constant.Conf;



@Controller
@SessionAttributes({Conf.SESSION_USERID})
@RequestMapping(value = "api/image")
public class ImageController {
	private final Logger LOG = LoggerFactory.getLogger(this.getClass());


	@Resource
	private WeixinService weixinService;

	/**
	 * 保存微信服务器的图片
	 * @param request
	 * @param session
	 * @param serverIds
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "downloadImg", produces = "text/plain;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public String downloadImg(HttpServletRequest request, HttpSession session,
			String serverIds) throws Exception {
		String accountId = (String) session.getAttribute("accountId");
		String ctxpath = request.getSession().getServletContext()
				.getRealPath("/");

		String apptoken = this.weixinService.getAccessToken(accountId)
				.getAccessToken();
		JSONArray jsonArray = new JSONArray();

		String[] serverId = serverIds.split(",");
		for (String sid : serverId) {
			try {
				String savePath = WeixinMediaUtil.download(sid, apptoken,
						ctxpath);
				jsonArray.put(savePath);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		return CreateResJosnUtil.createSuccessJson(null,
				new JSONObject().put("images", jsonArray)).toString();

	}
}
